package net.gooduo.spring_boot_template.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.gooduo.spring_boot_template.dto.AdminInfoDto;
import net.gooduo.spring_boot_template.entity.Admin;
import net.gooduo.spring_boot_template.exception.HttpException;
import net.gooduo.spring_boot_template.exception.HttpExceptionEnum;
import net.gooduo.spring_boot_template.mapper.AdminMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Service
public class AuthService {
    private final AdminMapper adminMapper;

    public AuthService(AdminMapper adminMapper) {
        this.adminMapper = adminMapper;
    }

    public String login(String username, String password) {
        Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username).last("limit 1"));
        if (admin == null || !BCrypt.checkpw(password, admin.getPassword())) {
            throw new HttpException(HttpExceptionEnum.WRONG_USERNAME_OR_PASSWORD);
        }
        StpUtil.login(admin.getId());
        return StpUtil.getTokenInfo().getTokenValue();
    }

    public AdminInfoDto info() {
        Admin admin = adminMapper.selectById(StpUtil.getLoginIdAsLong());
        AdminInfoDto dto = new AdminInfoDto();
        BeanUtils.copyProperties(admin, dto);
        return dto;
    }
}
